package cn.jilian.front.web;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.databind.ObjectMapper;

import cn.jilian.common.domain.R;
import cn.jilian.common.service.SMSService;
import cn.jilian.common.util.MD5Util;
import cn.jilian.entity.Auth;
import cn.jilian.entity.Driver;
import cn.jilian.entity.SupplierAdmin;
import cn.jilian.entity.SupplierUnit;
import cn.jilian.entity.TransAdmin;
import cn.jilian.entity.Unit;
import cn.jilian.entity.User;
import cn.jilian.front.domain.ApplyInfo;
import cn.jilian.front.domain.BizLicenseInfo;
import cn.jilian.front.domain.DriverApplyInfo;
import cn.jilian.front.domain.DriverLicense;
import cn.jilian.front.domain.DriverRegInfo;
import cn.jilian.front.domain.DrivingLicense;
import cn.jilian.front.domain.IdCardBackInfo;
import cn.jilian.front.domain.IdNoInfo;
import cn.jilian.front.domain.RegInfo;
import cn.jilian.front.service.BizlicenseService;
import cn.jilian.front.service.DriverLicenseService;
import cn.jilian.front.service.DrivingLicenseService;
import cn.jilian.front.service.IdCardService;
import cn.jilian.front.util.RandomCodes;
import cn.jilian.front.util.SessionUtil;
import cn.jilian.sys.service.UnitService;
import cn.jilian.sys.service.UserService;
import cn.jilian.trans.bizz.domain.TransUnit;
import io.swagger.annotations.ApiOperation;

@Controller
@RequestMapping("/reg")
public class RegController {
	
	public static final String EXPITR_TIME="expire_time";
	public static final String SUPPLIER_REG_INFO="supplierRegInfo";
	public static String REG_INFO="reg_info";
	
	@Autowired
	private BizlicenseService bizLicenseHandler;
	@Autowired
	private IdCardService idCardService;
	@Autowired
	private DrivingLicenseService drivingLicenseService;
	@Autowired
	private DriverLicenseService driverLicenseService;
	 
	@Autowired
	private SMSService smsService;
	
	@Autowired
	private UnitService unitService;
	
	@Autowired
	private UserService userService;
	

	
	@Autowired
	private ObjectMapper objectMapper;
	
	@Value("${app.login.url}")
	private String loginUrl;
	
	@Value("${tencent.sms.regTplId}")
	private String regTemplateId;
	
	
	@Value("${reg.sms.template}")
	private String regSmsTemplate;
	
	@Value("${reg.sms.duration}")
	private Long duration;
	
	@Value("${file.store.folder.path}")
	private String storeFolderPath;
	
	@ApiOperation(value="货源商-注册第一步",notes="验证手机号")
	@GetMapping("/supplier/page1.html")
	public String getReg1(Model model,HttpSession session) {
		model.addAttribute("loginUrl", loginUrl);
		RegInfo info=(RegInfo)session.getAttribute(REG_INFO);
		if(info!=null) {
			model.addAttribute("mobile", Objects.toString(info.getMobile(), ""));
		}
		return "supplier/reg1";
	}
	
	
	
	
	@PostMapping("/unit/step1")
	@ResponseBody
	public R postReg1(@RequestParam(name="mobile")String mobile,
			@RequestParam(name="authCode")String authCode,
			@RequestParam(name="smsCode")String smsCode,
			@RequestParam(name="password")String password,HttpSession session) {
		Boolean rs=SessionUtil.checkValidateCode(session, mobile, smsCode, authCode);
		if(rs) {
			Auth auth=userService.findByUsername(mobile);
			if(auth!=null) {
				return R.fail("该手机号已被注册");
			}
			RegInfo info=(RegInfo)session.getAttribute(REG_INFO);
			if(info==null) {
				info=new RegInfo();
				session.setAttribute(REG_INFO, info);
			}
			info.setMobile(mobile);
			info.setPassword(password);
			return R.ok;
		}else {
			return R.fail("未通过验证");
		}
	}
	
	
	
	@PostMapping("/supplier/backToPage2")
	public String backToPage2(ApplyInfo applyInfo,HttpSession session) {
		session.setAttribute(SUPPLIER_REG_INFO, applyInfo);
		return "redirect:/reg/supplier/page2.html";
	}
	
	 @ApiOperation(value = "获取当前会话已上传的营业执照", notes = "返回对应的文件流")
	 @GetMapping("/image/bizlicense")
	 public ResponseEntity<byte[]> getRegLicenseFile(HttpSession session){
	   try{
	    	RegInfo info=(RegInfo) session.getAttribute(REG_INFO);
	    		if(info!=null) {
	    			String path=info.getBizLicense();
	    			if(StringUtils.isNotBlank(path)) {
	    				File file=new File(path);
	    				if(file.exists()) {
	    					String ext=StringUtils.substringAfterLast(path, ".");
	    					byte[] body=FileUtils.readFileToByteArray(file);
	    					HttpHeaders headers = new HttpHeaders();
				             headers.add("Content-Disposition", "attachment;filename=bizlicense"+"."+ext);
				             HttpStatus statusCode = HttpStatus.OK;
				             ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
				             return entity;
	    				}
	    			}
		    		 
	    		}
	    		return null;
	    		
	    	}catch(Exception e){
	    		e.printStackTrace();
	    		return null;
	    	}
	}
	 
	 @ApiOperation(value = "获取当前会话已上传的法人正面照", notes = "返回对应的文件流")
	 @GetMapping("/image/repIdCardFront")
	 public ResponseEntity<byte[]> getRegRepIdCardFrontFile(HttpSession session){
	   try{
	    	RegInfo info=(RegInfo) session.getAttribute(REG_INFO);
	    		if(info!=null) {
	    			String path=info.getRepIdCardFront();
	    			if(StringUtils.isNotBlank(path)) {
	    				File file=new File(path);
	    				if(file.exists()) {
	    					String ext=StringUtils.substringAfterLast(path, ".");
	    					byte[] body=FileUtils.readFileToByteArray(file);
	    					HttpHeaders headers = new HttpHeaders();
				             headers.add("Content-Disposition", "attachment;filename=repIdCardFront"+"."+ext);
				             HttpStatus statusCode = HttpStatus.OK;
				             ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
				             return entity;
	    				}
	    			}
		    		 
	    		}
	    		return null;
	    		
	    	}catch(Exception e){
	    		e.printStackTrace();
	    		return null;
	    	}
	}
	
	 @ApiOperation(value = "获取当前会话已上传的法人背面照", notes = "返回对应的文件流")
	 @GetMapping("/image/repIdCardBack")
	 public ResponseEntity<byte[]> getRegRepIdCardBackFile(HttpSession session){
	   try{
	    	RegInfo info=(RegInfo) session.getAttribute(REG_INFO);
	    		if(info!=null) {
	    			String path=info.getRepIdCardBack();
	    			if(StringUtils.isNotBlank(path)) {
	    				File file=new File(path);
	    				if(file.exists()) {
	    					String ext=StringUtils.substringAfterLast(path, ".");
	    					byte[] body=FileUtils.readFileToByteArray(file);
	    					HttpHeaders headers = new HttpHeaders();
				             headers.add("Content-Disposition", "attachment;filename=repIdCardBack"+"."+ext);
				             HttpStatus statusCode = HttpStatus.OK;
				             ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
				             return entity;
	    				}
	    			}
		    		 
	    		}
	    		return null;
	    		
	    	}catch(Exception e){
	    		e.printStackTrace();
	    		return null;
	    	}
	}
	@ApiOperation(value="货源商-注册第二步",notes="上传证件")
	@GetMapping("/supplier/page2.html")
	public String getReg2(Model model,
			HttpSession session) {
		RegInfo info=(RegInfo) session.getAttribute(REG_INFO);
		if(info!=null) {
			if(StringUtils.isNotBlank(info.getBizLicense())) {
				model.addAttribute("bizlicense", true);
			}
			if(StringUtils.isNotBlank(info.getRepIdCardFront())) {
				model.addAttribute("repFront", true);
			}
			if(StringUtils.isNotBlank(info.getRepIdCardBack())) {
				model.addAttribute("repBack", true);
			}
			return "supplier/reg2";
		}
		else {
			return "redirect:/reg/supplier/page1.html";
		}
	}
	
	@ApiOperation(value="注册发送短信")
	@PostMapping("/sendSmsCode")
	@ResponseBody
	public R sendRegSmsCode(@RequestParam(name="mobile")String mobile,
			@RequestParam(name="authCode")String authCode,
			HttpSession session) {
		Auth auth=userService.findByUsername(mobile);
		if(auth!=null) {
			return R.fail("该手机号已被注册");
		}
		String ac=SessionUtil.getAuthCode(session);
		if(!StringUtils.equalsIgnoreCase(ac, authCode)) {
			return R.fail("图形验证码输入错误");
		}
		Object expire=session.getAttribute(EXPITR_TIME);
		if(expire!=null&&new Date().getTime()<(((Number)expire).longValue())) {
			return R.fail("发送太频繁，请稍后再试");
		}
		String smsCode=RandomStringUtils.randomNumeric(6);
		int rs=smsService.sendSmsCode(mobile, regTemplateId, smsCode);
		SessionUtil.cacheSmsCode(session, mobile, smsCode, duration);
		if(rs==0) {
			return R.ok;
		}else {
			return R.fail;
		}
	}
	
	@SuppressWarnings("unchecked")
	@ApiOperation(value="货源商-注册第三步",notes="完善注册信息")
	@GetMapping("/supplier/page3.html")
	public String reg3(Model model,HttpSession session) {
		RegInfo regInfo=(RegInfo) session.getAttribute(REG_INFO);
		if(regInfo==null) {
			return "redirect:/reg/supplier/page1.html";
		}else if(regInfo.getBizLicense()==null){
			return "redirect:/reg/supplier/page2.html";
		}
		ApplyInfo applyInfo=(ApplyInfo) session.getAttribute(SUPPLIER_REG_INFO);
		if(applyInfo==null) {
			applyInfo=new ApplyInfo();
			applyInfo.setContactMobile(regInfo.getMobile());
			BizLicenseInfo bizlicenseInfo=regInfo.getBizLicenseInfo();
			if(bizlicenseInfo!=null) {
				applyInfo.setCreditCode(bizlicenseInfo.getSocialCreditCode());
				applyInfo.setLocation(bizlicenseInfo.getAddress());
				applyInfo.setRepName(bizlicenseInfo.getLegalRepreName());
				applyInfo.setOrgName(bizlicenseInfo.getOrgName());
			}
			IdNoInfo idInfo=regInfo.getIdNoInfo();
			if(idInfo!=null) {
				applyInfo.setRepIdNo(idInfo.getIdNo());
			}
		}else {
			applyInfo.setContactMobile(regInfo.getMobile());
		}
		model.addAllAttributes(objectMapper.convertValue(applyInfo, Map.class));
		return "supplier/reg3";
	}
	
	@ApiOperation(value="货源商",notes="完成注册")
	@PostMapping("/supplier/complete")
	public String reg4(@Valid ApplyInfo applyInfo,HttpSession session,Model model) {
		model.addAttribute("loginUrl", loginUrl);
		if(applyInfo==null) {
			return "supplier/complete";
		}
		Unit unit=unitService.findByName(applyInfo.getOrgName());
		if(unit==null) {
			unit=new SupplierUnit();
		}
		unit.setText(applyInfo.getOrgName());
		unit.setAcctBank(applyInfo.getAcctBank());
		unit.setAcctNo(applyInfo.getAcctNo());
		unit.getContactInfo().setLocation(applyInfo.getLocation());
		unit.getContactInfo().setRepName(applyInfo.getRepName());
		unit.getContactInfo().setRepIdNo(applyInfo.getRepIdNo());
		unit.setMail(applyInfo.getEmail());
		unit.setCreditCode(applyInfo.getCreditCode());
		unit.getContactInfo().setRegAddr(applyInfo.getRegAddr());
		unit.getContactInfo().setContactName(applyInfo.getContactName());
		unit.getContactInfo().setContactMobile(applyInfo.getContactMobile());
		Long unitId=unit.getId();
		if(unitId!=null) {
			unitService.save(unit);
		}else {
			unitId=unitService.add(unit);
		}
		RegInfo regInfo=(RegInfo) session.getAttribute(REG_INFO);
		if(regInfo==null) {
			return "supplier/complete";
		}
		User user=new SupplierAdmin();
		user.setFullname(regInfo.getMobile());
		user.setUsername(regInfo.getMobile());
		user.setFid(unitId);
		user.setMobile(regInfo.getMobile());
		user.setUnitId(unitId);
		long userId=userService.addUser(user);
		if(userId>0) {
			Auth auth=new Auth();
			auth.setFid(userId);
			auth.setFail(0);
			auth.setHash(2);
			auth.setUsername(regInfo.getMobile());
			String salt=RandomStringUtils.randomAlphanumeric(6);
			auth.setSalt(salt);
			auth.setPass(MD5Util.GetMD5Code(regInfo.getPassword()+salt));
			userService.addAuth(auth);
		}
		return "supplier/complete";
	}
	
	
	@ApiOperation(value="承运方-注册第一步",notes="验证手机号")
	@GetMapping("/trans/page1.html")
	public String  regValidateMobile(Model model,HttpSession session) {
		model.addAttribute("loginUrl", loginUrl);
		RegInfo info=(RegInfo)session.getAttribute(REG_INFO);
		if(info!=null) {
			model.addAttribute("mobile", Objects.toString(info.getMobile(), ""));
		}
		return "trans/reg1";
	}
	
	
	@ApiOperation(value="承运方-注册第二步",notes="完善注册信息")
	@GetMapping("/trans/page2.html")
	public String  regFillDetail(Model model,
			HttpSession session) {
		RegInfo info=(RegInfo) session.getAttribute(REG_INFO);
		if(info!=null) {
			if(StringUtils.isNotBlank(info.getBizLicense())) {
				model.addAttribute("bizlicense", true);
			}
			if(StringUtils.isNotBlank(info.getRepIdCardFront())) {
				model.addAttribute("repFront", true);
			}
			if(StringUtils.isNotBlank(info.getRepIdCardBack())) {
				model.addAttribute("repBack", true);
			}
			return "trans/reg2";
		}
		else {
			return "redirect:/reg/trans/page1.html";
		}
	}
	
	@ApiOperation(value="承运方-注册第三步",notes="给出注册结果")
	@GetMapping("/trans/page3.html")
	public String  regResult(Model model,HttpSession session) {
		RegInfo regInfo=(RegInfo) session.getAttribute(REG_INFO);
		if(regInfo==null) {
			return "redirect:/reg/trans/page1.html";
		}else if(regInfo.getBizLicense()==null){
			return "redirect:/reg/trans/page2.html";
		}
		ApplyInfo applyInfo=(ApplyInfo) session.getAttribute(SUPPLIER_REG_INFO);
		if(applyInfo==null) {
			applyInfo=new ApplyInfo();
			applyInfo.setContactMobile(regInfo.getMobile());
			BizLicenseInfo bizlicenseInfo=regInfo.getBizLicenseInfo();
			if(bizlicenseInfo!=null) {
				applyInfo.setCreditCode(bizlicenseInfo.getSocialCreditCode());
				applyInfo.setLocation(bizlicenseInfo.getAddress());
				applyInfo.setRepName(bizlicenseInfo.getLegalRepreName());
				applyInfo.setOrgName(bizlicenseInfo.getOrgName());
			}
			IdNoInfo idInfo=regInfo.getIdNoInfo();
			if(idInfo!=null) {
				applyInfo.setRepIdNo(idInfo.getIdNo());
			}
		}else {
			applyInfo.setContactMobile(regInfo.getMobile());
		}
		model.addAllAttributes(objectMapper.convertValue(applyInfo, Map.class));
		return "trans/reg3";
	}
	
	@ApiOperation(value="物流公司",notes="完成注册")
	@PostMapping("/trans/complete")
	public String transreg4(ApplyInfo applyInfo,HttpSession session) {
		Unit unit=unitService.findByName(applyInfo.getOrgName());
		if(unit==null) {
			unit=new TransUnit();
		}
		unit.setText(applyInfo.getOrgName());
		unit.setAcctBank(applyInfo.getAcctBank());
		unit.setAcctNo(applyInfo.getAcctNo());
		unit.getContactInfo().setLocation(applyInfo.getLocation());
		unit.getContactInfo().setRepName(applyInfo.getRepName());
		unit.getContactInfo().setRepIdNo(applyInfo.getRepIdNo());
		unit.setMail(applyInfo.getEmail());
		unit.setCreditCode(applyInfo.getCreditCode());
		unit.getContactInfo().setRegAddr(applyInfo.getRegAddr());
		unit.getContactInfo().setContactName(applyInfo.getContactName());
		unit.getContactInfo().setContactMobile(applyInfo.getContactMobile());
		Long unitId=unit.getId();
		if(unitId!=null) {
			unitService.save(unit);
		}else {
			unitId=unitService.add(unit);
		}
		RegInfo regInfo=(RegInfo) session.getAttribute(REG_INFO);
		User user=new TransAdmin();
		user.setFullname(regInfo.getMobile());
		user.setUsername(regInfo.getMobile());
		user.setFid(unitId);
		user.setMobile(regInfo.getMobile());
		user.setUnitId(unitId);
		IdNoInfo idNoInfo=regInfo.getIdNoInfo();
		if(idNoInfo!=null) {
			if(StringUtils.isNoneBlank(idNoInfo.getBirth())) {
				try {
					Date birth=DateUtils.parseDate(idNoInfo.getBirth(), "yyyy-MM-dd");
					user.setBirth(birth);
				}catch(Exception e) {
					
				}
			}
			user.setGender(StringUtils.equals(idNoInfo.getGender(), "女")?2:1);
			user.setSurname(idNoInfo.getName());
		}
		long userId=userService.addUser(user);
		if(userId>0) {
			Auth auth=new Auth();
			auth.setFid(userId);
			auth.setFail(0);
			auth.setHash(2);
			auth.setUsername(regInfo.getMobile());
			String salt=RandomStringUtils.randomAlphanumeric(6);
			auth.setSalt(salt);
			auth.setPass(MD5Util.GetMD5Code(regInfo.getPassword()+salt));
			userService.addAuth(auth);
		}
		return "supplier/complete";
	}
	public static final String BIZLICENSEINFO="bizLicenseInfo";
	
	@ApiOperation(value = "注册上传营业执照", notes = "识别营业执照信息")
	@PostMapping("/upload/bizlicense")
	@ResponseBody
	public R uploadBizlicense(MultipartFile file,
			HttpSession session){
		try {
		RegInfo info=(RegInfo) session.getAttribute(REG_INFO);
		if(info==null) {
			return R.fail("请重新验证");
		}
		BizLicenseInfo bizLicenseInfo=bizLicenseHandler.handle(IOUtils.toByteArray(file.getInputStream()));
		String orgName=bizLicenseInfo.getOrgName();
		session.setAttribute(BIZLICENSEINFO, bizLicenseInfo);
		String ext=StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
		String path=storeFolderPath+"/bizlicense/"+orgName+"."+ext;
		File storefile=new File(path);
		IOUtils.copy(file.getInputStream(),FileUtils.openOutputStream(storefile));
		info.setBizLicense(path);
		info.setBizLicenseInfo(bizLicenseInfo);
		return R.ok(bizLicenseInfo);
		}catch(Exception e) {
			e.printStackTrace();
			return R.fail("服务出错，请重试");
		}
		
	}
	
	public static final String REPIDNO="repIdNo";
	
	@ApiOperation(value="上传企业法人身份证正面",notes="识别并验证身份证号")
	@PostMapping("/upload/repIdCardFront")
	@ResponseBody
	public R uploadOrgRepIdCardFront(MultipartFile file,
			HttpSession session){
		try {
			RegInfo reginfo=(RegInfo) session.getAttribute(REG_INFO);
			if(reginfo==null) {
				return R.fail("请重新验证");
			}
			String ext=StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
			String path=storeFolderPath+"/idCard/"+UUID.randomUUID()+"."+ext;
			File storefile=new File(path);
			FileUtils.copyInputStreamToFile(file.getInputStream(), storefile);
			IdNoInfo info=idCardService.handleFrontSide(storefile);
			String idNo=info.getIdNo();
			reginfo.setIdNoInfo(info);
			String realpath=storeFolderPath+"/idCard/"+idNo+"_front."+ext;
			File realfile=new File(realpath);
			storefile.renameTo(realfile);
			reginfo.setRepIdCardFront(path);
			return R.ok(info);
		}catch(Exception e) {
			e.printStackTrace();
			return R.fail("文件解析异常");
		}
	}
	
	@ApiOperation(value="上传企业法人身份证背面",notes="识别并验证身份证号")
	@PostMapping("/upload/repIdCardBack")
	@ResponseBody
	public R uploadOrgRepIdCardBack(MultipartFile file,
			HttpSession session){
		try {
			RegInfo reginfo=(RegInfo) session.getAttribute(REG_INFO);
			if(reginfo==null) {
				return R.fail("请重新验证");
			}
			String ext=StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
			String idNo=reginfo.getIdNoInfo().getIdNo();
			String path=storeFolderPath+"/idCard/"+idNo+"_back."+ext;
			File storefile=new File(path);
			IOUtils.copy(file.getInputStream(),FileUtils.openOutputStream(storefile));
			reginfo.setRepIdCardBack(path);
			return R.ok;
		}catch(Exception e) {
			e.printStackTrace();
			return R.fail("文件存储异常");
		}
	}
	
	 /**
     * 验证码图片
     */
    @GetMapping(value = "/vcode")
    public void authCodeImage(HttpServletResponse response, HttpSession session) {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        try {
            String authCode = RandomStringUtils.randomAlphanumeric(4);
            RandomCodes.drawImage(response.getOutputStream(), authCode);
            SessionUtil.cacheImageAuthCode(session,authCode);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    @GetMapping("/protocol.html")
    public String protocol() {
    	return "docs/protocol";
    }
    
    @PostMapping("/driver/step1")
	@ResponseBody
	public R driverpostReg1(@RequestParam(name="mobile")String mobile,
			@RequestParam(name="authCode")String authCode,
			@RequestParam(name="smsCode")String smsCode,
			@RequestParam(name="password")String password,HttpSession session) {
		Boolean rs=SessionUtil.checkValidateCode(session, mobile, smsCode, authCode);
		if(rs) {
			Auth auth=userService.findByUsername(mobile);
			if(auth!=null) {
				return R.fail("该手机号已被注册");
			}
			DriverRegInfo info=(DriverRegInfo)session.getAttribute(DRIVER_REG_INFO);
			if(info==null) {
				info=new DriverRegInfo();
				session.setAttribute(DRIVER_REG_INFO, info);
			}
			info.setMobile(mobile);
			info.setPassword(password);
			return R.ok;
		}else {
			return R.fail("未通过验证");
		}
	}
    
    @ApiOperation(value="司机-注册第一步",notes="验证手机号")
    @GetMapping("/driver/page1.html")
    public String driverReg1(Model model,HttpSession session) {
    	model.addAttribute("loginUrl", loginUrl);
    	DriverRegInfo info=(DriverRegInfo)session.getAttribute(DRIVER_REG_INFO);
		if(info==null) {
			info=new DriverRegInfo();
			session.setAttribute(DRIVER_REG_INFO, info);
			model.addAttribute("mobile", Objects.toString(info.getMobile(), ""));
		}
		return "driver/reg1";
	}
	
    @ApiOperation(value="司机-注册第二步",notes="上传证件")
	@GetMapping("/driver/page2.html")
	public String driverReg2(@RequestParam(required=false,name="errorMsg")String errorMsg,
			Model model,
			HttpSession session) {
    	DriverRegInfo info=(DriverRegInfo) session.getAttribute(DRIVER_REG_INFO);
		if(info!=null) {
			if(StringUtils.isNotBlank(info.getIdCardFront())) {
				model.addAttribute("idCardFront", true);
			}
			if(StringUtils.isNotBlank(info.getIdCardBack())) {
				model.addAttribute("idCardBack", true);
			}
			if(info.getDriverLicenseInfo()!=null) {
				model.addAttribute("driverLicense", true);
			}
			if(info.getDrivingLicenseInfo()!=null) {
				model.addAttribute("drivingLicense", true);
			}
			return "driver/reg2";
		}
		else {
			return "redirect:/reg/driver/page1.html";
		}
	}
    
    public static final String DRIVER_PAGE2_URL="redirect:/reg/driver/page1.html";
    
    @SuppressWarnings("unchecked")
	@ApiOperation(value="司机-注册第三步",notes="完善注册信息")
	@GetMapping("/driver/page3.html")
	public String  driverReg3(Model model,HttpSession session) {
		DriverRegInfo regInfo=(DriverRegInfo) session.getAttribute(DRIVER_REG_INFO);
		if(regInfo==null) {
			model.addAttribute("errorMsg", "会话超时，请重新验证");
			return "redirect:/reg/driver/page1.html";
		}
		String idCardFile=regInfo.getIdCardFront();
		if(StringUtils.isBlank(idCardFile)||!new File(idCardFile).exists()) {
			model.addAttribute("errorMsg", "请上传身份证");
			return DRIVER_PAGE2_URL;
		}
		
		if(regInfo.getIdNoInfo()==null){
			model.addAttribute("errorMsg", "请重新上传一张清晰的身份证");
			return DRIVER_PAGE2_URL;
		}
		String driverLicenseFile=regInfo.getDriverLicense();
		if(StringUtils.isBlank(driverLicenseFile)||!new File(driverLicenseFile).exists()) {
			model.addAttribute("errorMsg", "请上传驾驶证");
			return DRIVER_PAGE2_URL;
		}
		DriverLicense driverLicenseInfo=regInfo.getDriverLicenseInfo();
		if(driverLicenseInfo==null) {
			model.addAttribute("errorMsg", "请重新上传清晰的驾驶证");
			return DRIVER_PAGE2_URL;
		}
		
		if(!StringUtils.equalsIgnoreCase(regInfo.getName(), driverLicenseInfo.getName())) {
			model.addAttribute("errorMsg", "驾驶证与身份证的姓名不一致");
			return DRIVER_PAGE2_URL;
		}
		String drivingLicense=regInfo.getDrivingLicense();
		if(StringUtils.isBlank(drivingLicense)||!new File(drivingLicense).exists()) {
			model.addAttribute("errorMsg", "请先上传行驶证");
			return DRIVER_PAGE2_URL;
		}
		DrivingLicense drivingLicenseInfo=regInfo.getDrivingLicenseInfo();
		if(drivingLicenseInfo==null||StringUtils.isBlank(drivingLicenseInfo.getFlapperCode())) {
			model.addAttribute("errorMsg", "请重新上传清晰的行驶证");
			return DRIVER_PAGE2_URL;
		}
		
		if(!StringUtils.equals(regInfo.getName(), drivingLicenseInfo.getOwner())) {
			model.addAttribute("errorMsg", "身份证姓名与行驶证所有人姓名不一致,请重新上传");
			return DRIVER_PAGE2_URL;
		}
		if(StringUtils.equalsIgnoreCase(driverLicenseInfo.getName(), drivingLicenseInfo.getOwner())) {
			model.addAttribute("errorMsg", "驾驶证姓名与行驶证所有人姓名不一致,请重新上传");
			return DRIVER_PAGE2_URL;
		}
		
		model.addAllAttributes(objectMapper.convertValue(regInfo, Map.class));
		return "driver/reg3";
	}
    
    @ApiOperation(value="司机完成注册",notes="正式提交注册信息，完成注册")
    @PostMapping("/driver/complete")
    public String driverReg4(DriverApplyInfo applyInfo,Model model,HttpSession session) {
    	try {
    		DriverRegInfo regInfo=(DriverRegInfo) session.getAttribute(DRIVER_REG_INFO);
    		if(regInfo==null) {
    			model.addAttribute("errorMsg", "回话超时,请重新验证完成注册");
    			return "redirect:/reg/driver/page1.html";
    		}
    		
    		Driver driver=new Driver();
    		driver.setFullname(regInfo.getName());
    		driver.setMobile(regInfo.getMobile());
    		driver.setSurname(regInfo.getName());
    		DriverLicense driverInfo=regInfo.getDriverLicenseInfo();
    		if(driverInfo!=null) {
    			if(StringUtils.isNotBlank(driverInfo.getBirth())) {
    				try {
    				Date birth=DateUtils.parseDate(driverInfo.getBirth(), "yyyy-MM-dd","yyyy年MM月dd日");
    				driver.setBirth(birth);
    				}catch(Exception e) {
    					e.printStackTrace();
    				}
    			}
    			driver.setGender(StringUtils.equals("男", driverInfo.getGendar())?1:2);
    		}
    		
    		
    		driver.setUsername(regInfo.getMobile());
    		driver.setIdNo(regInfo.getIdNoInfo().getIdNo());
    		driver.setVehicleType(applyInfo.getCargoType());
    		driver.setVehicleLength(applyInfo.getVechicleLength());
    		driver.setVehicleWidth(applyInfo.getVechicleWidth());
    		driver.setAcctBank(applyInfo.getAcctBank());
    		driver.setDriverLicenseNo(regInfo.getDriverLicenseInfo().getCode());
    		driver.setAcctNo(applyInfo.getAcctNo());
    		driver.setDrivingLicenseNo(regInfo.getDrivingLicenseInfo().getIdentCode());
    		driver.setFlapperCode(regInfo.getDrivingLicenseInfo().getFlapperCode());
    		long userId=userService.addUser(driver);
    		Auth auth=new Auth();
    		auth.setFid(userId);
    		auth.setHash(2);
    		auth.setUsername(regInfo.getName());
    		String salt=RandomStringUtils.randomAlphanumeric(6);
    		auth.setSalt(salt);
    		String pass=MD5Util.GetMD5Code(applyInfo.getPassword()+salt);
    		auth.setPass(pass);
    		userService.addAuth(auth);
    		userService.addUser(driver);
    	}catch(Exception e) {
    		e.printStackTrace();
    	}
    	return "driver/complete";
    }
  
    
    @ApiOperation(value="上传司机行驶证件照",notes="识别并验证")
	@PostMapping("/upload/drivinglicense")
	@ResponseBody
	public R uploadDrivingLicense(MultipartFile file,
			HttpSession session){
		try {
			DriverRegInfo reginfo=(DriverRegInfo) session.getAttribute(DRIVER_REG_INFO);
			if(reginfo==null) {
				return R.fail("请重新验证");
			}
			DrivingLicense info=drivingLicenseService.handle(file.getBytes());
			if(info==null||StringUtils.isBlank(info.getOwner())||
					StringUtils.isBlank(info.getFlapperCode())) {
				return R.fail("行驶证无法清晰识别，请重新上传");
			}
			String ext=StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
			String idNo=info.getIdentCode();
			String path=storeFolderPath+"/drivinglicense/"+idNo+"."+ext;
			File storefile=new File(path);
			IOUtils.copy(file.getInputStream(),FileUtils.openOutputStream(storefile));
			reginfo.setDrivingLicense(path);
			reginfo.setDrivingLicenseInfo(info);
			String name=reginfo.getName();
			if(StringUtils.isNotBlank(name)&&!StringUtils.equals(name, info.getOwner())) {
				return R.fail("身份证信息与行驶证姓名信息不一致，请重新上传");
			}
			DriverLicense driverLicenseInfo=reginfo.getDriverLicenseInfo();
			if(driverLicenseInfo!=null&&StringUtils.equalsIgnoreCase(driverLicenseInfo.getName(), info.getOwner())) {
				return R.fail("行驶证与驾驶证姓名信息不一致，请重新上传");
			}
			return R.ok(info);
		}catch(Exception e) {
			e.printStackTrace();
			return R.fail("文件解析异常");
		}
	}
    
    @ApiOperation(value="上传司机驾驶证件照",notes="识别并验证")
	@PostMapping("/upload/driverlicense")
	@ResponseBody
	public R uploadDriverLicense(MultipartFile file,
			HttpSession session){
		try {
			DriverRegInfo reginfo=(DriverRegInfo) session.getAttribute(DRIVER_REG_INFO);
			if(reginfo==null) {
				return R.fail("请重新验证");
			}
			DriverLicense info=driverLicenseService.handle(file.getBytes());
			if(info==null||StringUtils.isBlank(info.getName())||
					StringUtils.isBlank(info.getVehicleType())) {
				return R.fail("驾驶证无法清晰识别，请重新上传");
			}
			String ext=StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
			String idNo=info.getCode();
			String path=storeFolderPath+"/driverlicense/"+idNo+"."+ext;
			File storefile=new File(path);
			IOUtils.copy(file.getInputStream(),FileUtils.openOutputStream(storefile));
			reginfo.setDriverLicense(path);
			reginfo.setDriverLicenseInfo(info);
			String name=reginfo.getName();
			
			if(StringUtils.isNotBlank(name)&&!StringUtils.equals(name, info.getName())) {
				return R.fail("身份证信息与驾驶证姓名信息不一致，请重新上传");
			}
			DrivingLicense drivingLicenseInfo=reginfo.getDrivingLicenseInfo();
			if(drivingLicenseInfo!=null&&StringUtils.equalsIgnoreCase(drivingLicenseInfo.getOwner(), info.getName())) {
				return R.fail("行驶证与驾驶证姓名信息不一致，请重新上传");
			}
			return R.ok(info);
		}catch(Exception e) {
			e.printStackTrace();
			return R.fail("文件解析异常");
		}
	}
    
    @ApiOperation(value="上传司机身份证正面",notes="识别并验证身份证号")
	@PostMapping("/upload/driverIdCardFront")
	@ResponseBody
	public R uploadDriverIdCardFront(MultipartFile file,
			HttpSession session){
		try {
			DriverRegInfo reginfo=(DriverRegInfo) session.getAttribute(DRIVER_REG_INFO);
			if(reginfo==null) {
				return R.fail("请重新验证");
			}
			String ext=StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
			String path=storeFolderPath+"/idCard/"+UUID.randomUUID()+"."+ext;
			File storefile=new File(path);
			FileUtils.copyInputStreamToFile(file.getInputStream(), storefile);
			IdNoInfo info=idCardService.handleFrontSide(storefile);
			
			String idNo=info.getIdNo();
			reginfo.setIdNoInfo(info);
			reginfo.setName(info.getName());
			reginfo.setIdNo(info.getIdNo());
			String realpath=storeFolderPath+"/idCard/"+idNo+"_front."+ext;
			File realfile=new File(realpath);
			storefile.renameTo(realfile);
			reginfo.setIdCardFront(realpath);
			return R.ok(info);
		}catch(Exception e) {
			e.printStackTrace();
			return R.fail("文件解析异常");
		}
	}
	
	@ApiOperation(value="上传司机身份证背面")
	@PostMapping("/upload/driverIdCardBack")
	@ResponseBody
	public R uploadDriverCardBack(MultipartFile file,
			HttpSession session){
		try {
			DriverRegInfo reginfo=(DriverRegInfo) session.getAttribute(DRIVER_REG_INFO);
			if(reginfo==null) {
				return R.fail("请重新验证");
			}
			if(StringUtils.isBlank(reginfo.getIdCardFront())) {
				return R.fail("请先上传身份证正面照");
			}
			String ext=StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
			IdNoInfo idCardInfo=reginfo.getIdNoInfo();
			String idNo=idCardInfo.getIdNo();
			String path=new StringBuilder(storeFolderPath).append("/idCard/")
					.append(UUID.randomUUID().toString()).append(".").append(ext)
					.toString();
			File storefile=new File(path);
			FileUtils.copyToFile(file.getInputStream(), storefile);
			IdCardBackInfo backInfo=idCardService.handleBackSide(storefile);
			if(backInfo==null) {
				return R.fail("无法正确识别此照片，请重新上传");
			}
			if(DateUtils.parseDate(backInfo.getExpireTime(),"yyyyMMdd").before(new Date())) {
				return R.fail("识别出该证件已失效，请更换后上传");
			}
			String realpath=storeFolderPath+"/idCard/"+idNo+"_back."+ext;
			storefile.renameTo(new File(realpath));
			reginfo.setIdCardBack(realpath);
			reginfo.setIdCardBackInfo(backInfo);
			String org=backInfo.getSigningOrg();
			org=StringUtils.substringBeforeLast(org, "公安局");
			String addr=idCardInfo.getAddr();
			if(!StringUtils.contains(addr, org)) {
				return R.fail("检测到身份证背面与正面所属户籍信息不配置");
			}
			return R.ok;
		}catch(Exception e) {
			e.printStackTrace();
			return R.fail("文件存储异常");
		}
	}
	
	public static final String DRIVER_REG_INFO="driverRegInfo";
	
	@ApiOperation(value="司机注册返回第二步")
	@PostMapping("/driver/backToPage2")
	public String driverBackToPage2(ApplyInfo applyInfo,HttpSession session) {
		DriverRegInfo regInfo=(DriverRegInfo) session.getAttribute(DRIVER_REG_INFO);
		if(regInfo==null) {
			return "redirect:/reg/driver/page1.html";
		}
		BeanUtils.copyProperties(applyInfo, regInfo);
		return "redirect:/reg/driver/page2.html";
	}
	
	 @ApiOperation(value = "获取当前会话已上传的司机正面照", notes = "返回对应的文件流")
	 @GetMapping("/image/driverCardFront")
	 public ResponseEntity<byte[]> getRegDriverIdCardFrontFile(HttpSession session){
	   try{
		   DriverRegInfo info=(DriverRegInfo) session.getAttribute(DRIVER_REG_INFO);
	    		if(info!=null) {
	    			String path=info.getIdCardFront();
	    			if(StringUtils.isNotBlank(path)) {
	    				File file=new File(path);
	    				if(file.exists()) {
	    					String ext=StringUtils.substringAfterLast(path, ".");
	    					byte[] body=FileUtils.readFileToByteArray(file);
	    					HttpHeaders headers = new HttpHeaders();
				             headers.add("Content-Disposition", "attachment;filename=idCardFront"+"."+ext);
				             HttpStatus statusCode = HttpStatus.OK;
				             ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
				             return entity;
	    				}
	    			}
		    		 
	    		}
	    		return null;
	    		
	    	}catch(Exception e){
	    		e.printStackTrace();
	    		return null;
	    	}
	}
	
	 @ApiOperation(value = "获取当前会话已上传的司机背面照", notes = "返回对应的文件流")
	 @GetMapping("/image/driverIdCardBack")
	 public ResponseEntity<byte[]> getRegDriverIdCardBackFile(HttpSession session){
	   try{
		   DriverRegInfo info=(DriverRegInfo) session.getAttribute(DRIVER_REG_INFO);
	    		if(info!=null) {
	    			String path=info.getIdCardBack();
	    			if(StringUtils.isNotBlank(path)) {
	    				File file=new File(path);
	    				if(file.exists()) {
	    					String ext=StringUtils.substringAfterLast(path, ".");
	    					byte[] body=FileUtils.readFileToByteArray(file);
	    					HttpHeaders headers = new HttpHeaders();
				             headers.add("Content-Disposition", "attachment;filename=driverIdCardBack"+"."+ext);
				             HttpStatus statusCode = HttpStatus.OK;
				             ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
				             return entity;
	    				}
	    			}
		    		 
	    		}
	    		return null;
	    		
	    	}catch(Exception e){
	    		e.printStackTrace();
	    		return null;
	    	}
	}
	 
	 @ApiOperation(value = "获取当前会话已上传的驾驶证照", notes = "返回对应的文件流")
	 @GetMapping("/image/driverlicense")
	 public ResponseEntity<byte[]> getRegDriverLicenseFile(HttpSession session){
	   try{
		   DriverRegInfo info=(DriverRegInfo) session.getAttribute(DRIVER_REG_INFO);
	    		if(info!=null) {
	    			String path=info.getDriverLicense();
	    			if(StringUtils.isNotBlank(path)) {
	    				File file=new File(path);
	    				if(file.exists()) {
	    					String ext=StringUtils.substringAfterLast(path, ".");
	    					byte[] body=FileUtils.readFileToByteArray(file);
	    					HttpHeaders headers = new HttpHeaders();
				             headers.add("Content-Disposition", "attachment;filename=driverLicense"+"."+ext);
				             HttpStatus statusCode = HttpStatus.OK;
				             ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
				             return entity;
	    				}
	    			}
		    		 
	    		}
	    		return null;
	    		
	    	}catch(Exception e){
	    		e.printStackTrace();
	    		return null;
	    	}
	}
	 
	 @ApiOperation(value = "获取当前会话已上传的行驶证照", notes = "返回对应的文件流")
	 @GetMapping("/image/drivinglicense")
	 public ResponseEntity<byte[]> getRegDrivingLicenseFile(HttpSession session){
	   try{
		   DriverRegInfo info=(DriverRegInfo) session.getAttribute(DRIVER_REG_INFO);
	    		if(info!=null) {
	    			String path=info.getDrivingLicense();
	    			if(StringUtils.isNotBlank(path)) {
	    				File file=new File(path);
	    				if(file.exists()) {
	    					String ext=StringUtils.substringAfterLast(path, ".");
	    					byte[] body=FileUtils.readFileToByteArray(file);
	    					HttpHeaders headers = new HttpHeaders();
				             headers.add("Content-Disposition", "attachment;filename=drivingLicense"+"."+ext);
				             HttpStatus statusCode = HttpStatus.OK;
				             ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
				             return entity;
	    				}
	    			}
		    		 
	    		}
	    		return null;
	    		
	    	}catch(Exception e){
	    		e.printStackTrace();
	    		return null;
	    	}
	}
}
